<?php

require_once(dirname(__FILE__).'/include/common.php');
require_once(dirname(__FILE__).'/include/backup.class.php');
if ($_SESSION['eptime_adminPower']<>0) {LYG::ShowMsg('您没有权限！');} 
error_reporting(0);
define('BACKUP_DIR','data_backup');

$webconfig = lyg::readArr("web");
define('EXTENTION',$webconfig['backrestore_ext']);

if(!empty($_POST)){
	
	$action = empty($_POST['action'])?"":$_POST['action'];

	if($action == "backup"){
		//执行备份
		set_time_limit(0);
		$res = db_backup();
		if($res['flag']){
			lyg::showmsg('备份成功，文件名：'.$res['info']);
		}else{
			lyg::showmsg('备份失败，请重试');
		}
	}else if($action == "restore"){
		set_time_limit(0);
		if(empty($_POST['backfile'])){
			lyg::showmsg('请选择要还原的数据文件');
		}

		$msg = db_restore(BACKUP_DIR."/".$_POST['backfile']);
		lyg::showmsg($msg);

	}else if($action == "delete"){
//加一个字符过滤到点和斜杠
		if(!preg_match('/./',$_POST['backfile'])){
			lyg::showmsg('不允许的字符');
		}
		if(empty($_POST['backfile'])){ lyg::showmsg('请选择要删除的数据文件'); }
		@unlink(BACKUP_DIR."/".$_POST['backfile']);
		lyg::jump("config_system_backrestore.php");
	}else if($action == "download"){
		if(empty($_POST['backfile'])){ lyg::showmsg('请选择要下载的数据文件'); }
//加一个字符过滤到点和斜杠
		$filename = BACKUP_DIR."/".$_POST['backfile'];
		$file_text = file_get_contents($filename);
		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Content-Disposition:attachment;filename=".$_POST['backfile']);
		header("Expires: 0");
		header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
		header("Pragma:public");
		echo $file_text;
		exit();
	}else if($action == "backup1"){
     $rowscount = $con->Excute("delete from #__money");
	 $rowscount1 = $con->Excute("delete from #__money_pay");
     $rowscount2=$rowscount+$rowscount1;
     LYG::ShowMsg("成功删除 {$rowscount2} 条记录!");
	}else if($action == "backup2"){
     $rowscount = $con->Excute("delete from #__zhanghu");
	 $rowscount1 = $con->Excute("delete from #__zhanghu_class");
     $rowscount2=$rowscount+$rowscount1;
     LYG::ShowMsg("成功删除 {$rowscount2} 条记录!");
	}else if($action == "backup3"){
     $rowscount = $con->Excute("delete from #__money_bigclass");
	 $rowscount1 = $con->Excute("delete from #__money_smallclass");
     $rowscount2=$rowscount+$rowscount1;
     LYG::ShowMsg("成功删除 {$rowscount2} 条记录!");
	}else if($action == "backup4"){
     $rowscount = $con->Excute("delete from #__wanglai");
     LYG::ShowMsg("成功删除 {$rowscount} 条记录!");
	}else if($action == "backup5"){
     $rowscount = $con->Excute("delete from #__yuangong");
     LYG::ShowMsg("成功删除 {$rowscount} 条记录!");
	}else if($action == "backup6"){
     $rowscount = $con->Excute("delete from #__xiangmu");
     LYG::ShowMsg("成功删除 {$rowscount} 条记录!");
	}else if($action == "backup7"){
     $rowscount = $con->Excute("delete from #__log");
     LYG::ShowMsg("成功删除 {$rowscount} 条记录!");
	}
	else{
		lyg::showmsg('未知操作');
	}
	
}

$backup_files = readbackfile();

function readbackfile(){
	$res = array();
	if(!is_dir(BACKUP_DIR)){ return $res; }
	$dh = opendir(BACKUP_DIR);
	while (($file = readdir($dh)) !== false) {
		if($file=="." || $file==".." || strpos($file,EXTENTION) === false || strpos($file,EXTENTION) != strlen($file) - strlen(EXTENTION)){ continue; }
		$res[] = array(
			"name"	=> $file,
			"path"	=> $file,
			"size"	=> strsize(filesize(BACKUP_DIR."/".$file)),
			"time"	=> filectime(BACKUP_DIR."/".$file),//创建时间
		);
	}
	closedir($dh);
	return $res;
}

function db_backup(){
	$res = array(
		'flag' => false,
		'info' => ''
	);
	$configInfo = init_read_install_config();
	$pm = array(
		'host' => $configInfo['host'],
		'uid' => $configInfo['user'],
		'pwd' => $configInfo['pwd'],
		'databases' => $configInfo['database'],
		'port' => $configInfo['port'],
		'extention' => EXTENTION
	);
	$success = false;
	$backPath =  BACKUP_DIR;
	try{
		$hp = new Sevstudio\MySQLHelper($pm);
		$success = $hp->BackUp($backPath);
		$res['flag'] = $success;
		if($success){
			$res['info'] = $hp->SucBackUpFilePaths[0];
		}		
	}catch(Exception $e){
		
	}
	return $res;
}
function db_restore($filename){

	if(!file_exists($filename)){ return "数据文件不存在"; }
	
	$configInfo = init_read_install_config();
	$pm = array(
		'host' => $configInfo['host'],
		'uid' => $configInfo['user'],
		'pwd' => $configInfo['pwd'],
		'databases' => $configInfo['database'],
		'port' => $configInfo['port'],
		'extention' => EXTENTION
	);
	
	$backPath = BACKUP_DIR;
	try{
		$hp = new Sevstudio\MySQLHelper($pm);
		$result = $hp->Restore($filename);
		$suc = $result['success'] + $result['error'];
		return "还原成功，共处理 $suc 条命令，成功 {$result['success']} 条，失败 {$result['error']} 条";
	}catch(Exception $e){ }
	return '还原失败';
	
}
//尺寸转换
function strsize($size = 0){
	$size = floatval($size);
	if($size<1024){
		return $size."b";
	}else if($size<1024*1024){
		$s = round($size / 1024,0);
		return $s."kb";
	}else{
		$s = round($size / 1024*1024,0);
		return $s."m";
	}
}
	
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>数据备份</title>
<link href="style/css/css.css" rel="stylesheet" type="text/css" />
<style type="text/css">
input.btn{ font-size:14px; background: #004B8B; color:#ffffff; line-height: 1em;padding:12px 50px; border: 0 }
input.btn1{ font-size:14px; background: #00ADC4; color:#ffffff; line-height: 1em;padding:12px 10px; border: 0 }
input.btn:active{ background:#3a79af;}
p.des{ font-size: 14px; line-height: 1em; padding:0px 0 20px; text-align: left; }
table.backup-list{ border: 0 }
table.backup-list td{ text-align: left; border-width: 1px 0 0; border-style: solid; border-color:#eaeaea;}
a.to-restore{ color: green; display: inline-block; margin-right: 10px;}
a.to-download{ color: #004B8B; display: inline-block; margin-right: 10px;}
a.to-delete{ color: red; }

#loading{ position: fixed; width: 100%; height: 100%; left: 0; top: 0; z-index: 9999999999999999; }
#loading span{ display:block;position: absolute;  width:50px; height: 50px; left: 50%; 
	margin-left: -25px; top: 50%; margin-top: -25px; }
#loading span:before{
	content: '';display: block; width: 10px; height:10px; 
	position: absolute; right:50%; top: 50%;margin-top:-5px;
	background:#0086C9; border-radius: 50%;
	animation:fangda 1s infinite;
	-webkit-animation:fangda 1s infinite;
}
#loading span:after{
	content: '';display: block; width: 20px; height:20px; 
	position: absolute; left:50%; top: 50%;margin-top:-10px;
	background:#64D214; border-radius: 50%;
	animation:suoxiao 1s infinite;
	-webkit-animation:suoxiao 1s infinite;
}

</style>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
	$("#to-backup").click(function(){
		document.postform.action.value = "backup";
		document.postform.submit();
	});
	$("a.to-restore").click(function(){
		if(!confirm('该操作会清空现有数据，确定还原该备份吗？\n还原过程请不要刷新浏览器！')){ return; }
		var file = $(this).parent().parent().attr('data-file');
		document.postform.action.value = "restore";
		document.postform.backfile.value = file;
		document.postform.submit();
	});
	$("a.to-delete").click(function(){
		if(!confirm('确定删除该备份吗？')){ return; }
		var file = $(this).parent().parent().attr('data-file');
		document.postform.action.value = "delete";
		document.postform.backfile.value = file;
		document.postform.submit();
	});
	$("a.to-download").click(function(){
		var file = $(this).parent().parent().attr('data-file');
		document.postform.action.value = "download";
		document.postform.backfile.value = file;
		document.postform.submit();
	});
		$("#to-backup1").click(function(){
		if(!confirm('确定清除业务数据吗？')){ return; }
		var file = $(this).parent().parent().attr('backup1');
		document.postform.action.value = "backup1";
		document.postform.submit();
	});
		$("#to-backup2").click(function(){
		if(!confirm('确定清除资金账户吗？')){ return; }
		var file = $(this).parent().parent().attr('backup2');
		document.postform.action.value = "backup2";
		document.postform.submit();
	});
		$("#to-backup3").click(function(){
		if(!confirm('确定清除一级和二级分类吗？')){ return; }
		var file = $(this).parent().parent().attr('backup3');
		document.postform.action.value = "backup3";
		document.postform.submit();
	});
		$("#to-backup4").click(function(){
		if(!confirm('确定清除<?php echo $webconfig['system_wanglai'];?>吗？')){ return; }
		var file = $(this).parent().parent().attr('backup4');
		document.postform.action.value = "backup4";
		document.postform.submit();
	});
		$("#to-backup5").click(function(){
		if(!confirm('确定清除<?php echo $webconfig['system_yuangong'];?>吗？')){ return; }
		var file = $(this).parent().parent().attr('backup5');
		document.postform.action.value = "backup5";
		document.postform.submit();
	});
		$("#to-backup6").click(function(){
		if(!confirm('确定清除<?php echo $webconfig['system_xiangmu'];?>吗？')){ return; }
		var file = $(this).parent().parent().attr('backup6');
		document.postform.action.value = "backup6";
		document.postform.submit();
	});
		$("#to-backup7").click(function(){
		if(!confirm('确定清除操作日志吗？')){ return; }
		var file = $(this).parent().parent().attr('backup7');
		document.postform.action.value = "backup7";
		document.postform.submit();
	});
});
</script>
</head>

<form method="post" name="postform">
	<input type="hidden" name="action">
	<input type="hidden" name="backfile">
	<input type="hidden" name="id">
</form>



<body class="content">

	<div class="message-box">
		<div class="message-title"><span>初始化数据</span></div>
		<div class="message-content">
			<div style="padding:10px 0; text-align: center;">
	<input type="submit" class="btn1" id="to-backup1" value="清除业务数据(包括收支、应收付、已收付)">	
	<input type="submit" class="btn1" id="to-backup2" value="清除资金账户(包括账号类型)">
    <input type="submit" class="btn1" id="to-backup3" value="清除一级和二级分类"> 
	<input type="submit" class="btn1" id="to-backup4" value="清除<?php echo $webconfig['system_wanglai'];?>">
	<input type="submit" class="btn1" id="to-backup5" value="清除<?php echo $webconfig['system_yuangong'];?>">
	<input type="submit" class="btn1" id="to-backup6" value="清除<?php echo $webconfig['system_xiangmu'];?>">
	<input type="submit" class="btn1" id="to-backup7" value="清除操作日志">
				<p style="color:red; line-height: 1em;padding:20px 0 0; font-size:14px;">确认开始正式使用该系统时执行数据初始化，选择对应项目会将相关数据清空。</p>
			</div>
		</div>
	</div>
<div style="height: 20px;"></div>
	<div class="message-box">
		<div class="message-title"><span>数据备份</span></div>
		<div class="message-content">
			<div style="padding:10px 0; text-align: center;">
				<input type="submit" class="btn" id="to-backup" value="执行备份">
				<p style="color:red; line-height: 1em;padding:20px 0 0; font-size:14px;">备份过程请不要刷新浏览器，直到提示备份成功。</p>
			</div>
		</div>
	</div>
	<div style="height: 20px;"></div>

	<div class="message-box">
		<div class="message-title"><span>数据还原</span></div>
		<div class="message-content">
			<div style="padding:30px 30px; text-align: center;">
				<?php if(count($backup_files)>0){ ?>
				<p class="des" style="color:red;">还原过程请不要刷新浏览器，直到提示成功！</p>
				<table class="backup-list">
					<tr>
						<td><b>备份文件</b></td>
						<td><b>文件大小</b></td>
						<td><b>备份时间</b></td>
						<td>&nbsp;</td>
					</tr>
					<?php
					foreach($backup_files as $k=>$v){
						$size = $v['size'];
						$time = $v['time']?date("Y-m-d H:i:s",$v['time']):"";
						$name = str_replace(EXTENTION,'',$v['name']);
						echo <<<TR
						<tr data-file="{$v['path']}">
							<td>{$name}</td>
							<td>{$size}</td>
							<td>{$time}</td>
							<td style="text-align:right">
								<a href="javascript:;" class="to-restore">还原该备份</a>
								<a href="javascript:;" class="to-download">下载该备份</a>
								<a href="javascript:;" class="to-delete">删除该备份</a>
							</td>
						</tr>
TR;
					}
					?>
					
				</table>
				<?php
				} else {
					echo "<p>暂无备份</p>";
				}
				?>
			</div>
		</div>

	</div>

	
</body>
</html>